package cn.db101.kaoqinserver.controller;

import cn.db101.kaoqinserver.config.ApiResult;
import cn.db101.kaoqinserver.model.response.FileResponse;
import cn.db101.kaoqinserver.model.response.ImageCaptcha;
import cn.db101.kaoqinserver.service.UserService;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("v1/kaoqin/file")
public class FileController {

    @Autowired
    private UserService userService;

    @PostMapping("upload")
    public ApiResult<FileResponse> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {

        //获取项目运行的绝对路径
        String filePath = System.getProperty("user.dir");

        //获取文件原始的名称
        String originFileName = file.getOriginalFilename();

        String yyyyMMdd = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        //声明一个保存目录的路径
        String dirPath = filePath + "\\src\\main\\resources\\static\\images\\" + yyyyMMdd;
        //创建一个文件或者文件夹的操作对象
        File dirFile = new File(dirPath);

        //判断文件是否存在 不存在的话执行下面的代码
        if (!dirFile.exists()) {
            //创建这个目录
            dirFile.mkdirs();
        }

        FileUtil.writeBytes(file.getBytes(), dirPath + "\\" + originFileName);

        FileResponse fileResponse = new FileResponse();
        fileResponse.setUrl("http://localhost:8078/images/" + yyyyMMdd + "/" + originFileName);
        fileResponse.setFileName(originFileName);

        return ApiResult.ofSuccess(fileResponse);

    }

    /**
     * 获取验证码
     */
    @GetMapping("captcha/img")
    public ApiResult<ImageCaptcha> getCaptchaImg(@RequestParam("width") int width, @RequestParam("height") int height) {

        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(width, height, 4, 10);

        String randomString = RandomUtil.randomString(6);
        ImageCaptcha imageCaptcha = new ImageCaptcha();
        imageCaptcha.setImg(lineCaptcha.getImageBase64Data());
        imageCaptcha.setId(randomString);
        userService.setCaptcha(randomString, lineCaptcha.getCode());

        return ApiResult.ofSuccess(imageCaptcha);
    }

}
